<template>
  <div>
    <div style="display: flex; justify-content: space-between">
      <!-- 添加按钮 -->
      <el-button type="primary" @click="handleAdd" style="margin: 10px 0">
        添加
      </el-button>
      <!-- 搜索框 -->
      <div>
        <el-input
          v-model="search"
          placeholder="搜索分类"
          style="width: 200px"
        />
        <el-button type="primary" @click="handleSearch">搜索</el-button>
      </div>
    </div>
    <!-- 表格 -->
    <GenericTable :data="tableData" :columns="columns" :pagination="pagination">
      <template #actions="scope">
        <el-button type="danger" @click="handleDelete(scope.row)"
          >删除</el-button
        >
        <el-button type="primary" @click="handleEdit(scope.row)"
          >编辑</el-button
        >
      </template>
      <!-- 图片 -->
      <template #image="scope">
        <!-- 字符串拼接 -->
        <el-image
          style="width: 50px; height: 50px"
          :src="`${baseUrl}/${scope?.row?.images[0]?.image?.filepath}`"
        />
      </template>
      <!-- 上传图片 -->
      <template #upload="scope">
        <el-upload
          class="avatar-uploader"
          :action="action"
          :data="{ categoryId: scope.row.id }"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :headers="uploadHeaders"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </template>
      <template #pagination>
        <!-- 自定义分页内容 -->
        <el-pagination
          :current-page="pagination.currentPage"
          :page-size="pagination.pageSize"
          :total="pagination.total"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
        />
      </template>
    </GenericTable>

    <!-- 弹窗 -->
    <GenericDialogForm
      :dialogTitle="isEdit ? '编辑分类' : '添加分类'"
      :dialogWidth="'30%'"
      v-model:visible="dialogVisible"
      :formData="isEdit ? editFormData : formData"
      :formFields="formFields"
      :formRules="formRules"
      @confirm="handleConfirm"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import GenericDialogForm from "@/component/GenericDialogForm.vue";
import GenericTable from "@/component/GenericTable.vue";
import Swal from "sweetalert2";
import { useCategoryStore } from "@/store/categoryStore";
import type { Category } from "@/service/login/types";
import cache from "@/utils/cache";
import {
  addCategoryAPI,
  editCategoryAPI,
  deleteCategoryAPI,
  searchCategoryAPI,
} from "@/service/login/category";
import { Plus } from "@element-plus/icons-vue";
// 初始化
const token = cache.getCache("token");
onMounted(async () => {
  await getCategory(1, 10);
});
// 获取分类
const categoryStore = useCategoryStore();
// 获取分类
const getCategory = async (page: number, pageSize: number) => {
  await categoryStore.getCategoryList(page, pageSize, token);
  tableData.value = categoryStore.categoryList;
  pagination.value.total = categoryStore.total;
  pagination.value.currentPage = page; // 确保初始页为1
  pagination.value.totalPages = categoryStore.totalPages;
};

// 弹窗是否可见
const dialogVisible = ref(false);

// 表格数据
const tableData = ref<Category[]>([]);

// 表格列
const columns = ref([
  { label: "ID", prop: "id" },
  { label: "分类名称", prop: "title" },
]);

// 分页
const pagination = ref({
  totalPages: 1, // 总页数
  pageSize: 10, // 每页条数
  total: 0, // 总条数
  currentPage: 1, // 当前页
});
// 是否编辑
const isEdit = ref(false);
// 添加表单数据
const formData = ref({
  title: "",
});
// 编辑表单数据
const editFormData = ref({
  id: 0,
  title: "",
});
// 表单规则
const formRules = ref({
  title: [{ required: true, message: "请输入分类名称", trigger: "blur" }],
});

// 表单字段
const formFields = ref([{ label: "分类名称", prop: "title", type: "input" }]);
// 添加按钮
const handleAdd = () => {
  dialogVisible.value = true;
  isEdit.value = false;
};

// 编辑按钮
const handleEdit = (row: any) => {
  dialogVisible.value = true;
  isEdit.value = true;
  editFormData.value = row;
};

// 确认按钮
const handleConfirm = async () => {
  if (isEdit.value) {
    const res = await editCategoryAPI(
      editFormData.value.id,
      editFormData.value.title,
      token
    );
    if (res.statusCode === 200) {
      dialogVisible.value = false;
      Swal.fire({
        title: "编辑成功",
        icon: "success",
      });
      await getCategory(
        pagination.value.currentPage,
        pagination.value.pageSize
      );
    } else {
      Swal.fire({
        title: "编辑失败",
        icon: "error",
      });
    }
  } else {
    const res = await addCategoryAPI(formData.value.title, token);
    if (res.statusCode === 200) {
      dialogVisible.value = false;
      Swal.fire({
        title: "添加成功",
        icon: "success",
      });
      await getCategory(
        pagination.value.currentPage,
        pagination.value.pageSize
      );
    } else {
      Swal.fire({
        title: "添加失败",
        icon: "error",
      });
    }
  }
};
// 删除按钮
const handleDelete = (row: any) => {
  Swal.fire({
    title: "确定删除吗？",
    icon: "warning",
    showCancelButton: true,
    confirmButtonText: "确定",
    cancelButtonText: "取消",
  }).then(async (result) => {
    if (result.isConfirmed) {
      const res = await deleteCategoryAPI(row.id, token);
      if (res.statusCode === 200) {
        Swal.fire({
          title: "删除成功",
          icon: "success",
        });
        await getCategory(
          pagination.value.currentPage,
          pagination.value.pageSize
        );
      } else {
        Swal.fire({
          title: "删除失败",
          icon: "error",
        });
      }
    }
  });
};

// 分页
const handlePageChange = async (page: number) => {
  pagination.value.totalPages = page;
  await getCategory(page, pagination.value.pageSize);
};

// 分页大小
const handleSizeChange = (size: number) => {
  pagination.value.pageSize = size;
  console.log(size, "分页大小");
};

// 搜索
const search = ref("");
// 搜索按钮
const handleSearch = async () => {
  const res = await searchCategoryAPI(search.value, token);
  if (res.statusCode === 200) {
    Swal.fire({
      title: "搜索成功",
      icon: "success",
    });
    console.log(res.data);
  } else {
    Swal.fire({
      title: "搜索失败",
      icon: "error",
    });
  }
};
const baseUrl = import.meta.env.VITE_API_BASE_URL;
// 上传图片
const imageUrl = ref("");
const action = computed(() => {
  return `${baseUrl}/upload/category`;
});
const uploadHeaders = computed(() => {
  return {
    Authorization: `Bearer ${token}`, // 将 token 添加到请求头
  };
});
// 上传图片前
const beforeAvatarUpload = (rawFile: any) => {
  const isImage = /image\/(jpeg|png)/.test(rawFile.type);
  const isLt2M = rawFile.size / 1024 / 1024 < 2;
  if (!isImage) {
    Swal.fire({
      title: "失败",
      text: "上传头像图片只能是 JPG/PNG 格式!",
      icon: "error",
    });
    return false;
  }
  if (!isLt2M) {
    Swal.fire({
      title: "失败",
      text: "上传头像图片大小不能超过 2MB!",
      icon: "error",
    });
    return false;
  }
  return true;
};
// 上传图片成功
const handleAvatarSuccess = (response: any, file: any, row: any) => {
  if (response.statusCode === 200) {
    getCategory(pagination.value.currentPage, pagination.value.pageSize);
    Swal.fire({
      title: "成功",
      text: "上传成功",
      icon: "success",
    });
  } else {
    Swal.fire({
      title: "失败",
      text: "上传失败",
      icon: "error",
    });
  }
};
</script>
<style scoped>
.avatar-uploader {
  width: 50px;
  height: 50px;
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  overflow: hidden;
  position: relative;
}

.avatar {
  width: 100%;
  height: 100%;
  display: block;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>
